package com.softserveinc.appwidget;

import java.util.ArrayList;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.SystemClock;
import android.util.Log;

import com.softserveinc.MovieManagerApplication;
import com.softserveinc.settings.AppWidgetSettingManager;

public class MovieManagerWidgetMediator {
	private static final String TAG = MovieManagerWidgetMediator.class
			.getSimpleName();

	private static final String UPDATE_SERVICE_WIDGET_DATA = "com.softserveinc.appWidget: ";

	private final List<Integer> registeredWidgets = new ArrayList<Integer>();

	private final AppWidgetSettingManager widgetSettingManager;

	private final Context context;

	public MovieManagerWidgetMediator(final Context context) {
		this.context = context;

		widgetSettingManager = ((MovieManagerApplication) context)
				.getWidgetSettingManager();
	}

	public void registerUIUpdateServiceIfNeeded(final Intent intent) {
		int appWidgetId = intent.getIntExtra(
				AppWidgetManager.EXTRA_APPWIDGET_ID,
				AppWidgetManager.INVALID_APPWIDGET_ID);

		Log.i(TAG, "setupUpdateServiceIfNeeded");

		if (registeredWidgets.contains(appWidgetId)) {
			unregisterWidgetServices(appWidgetId);
		}

		Intent serviceIntent = new Intent(context, WidgetUpdateService.class);
		serviceIntent
				.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

		serviceIntent.setData(Uri.parse(UPDATE_SERVICE_WIDGET_DATA
				+ appWidgetId));

		PendingIntent pendingIntent = PendingIntent.getService(context, 0,
				serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);

		AlarmManager alarmManager = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);

		int period = widgetSettingManager
				.getUpdateUIDataPeriodInMilieconds(appWidgetId);

		alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
				SystemClock.elapsedRealtime(), period, pendingIntent);

		registeredWidgets.add(appWidgetId);
	}

	public void unregisterWidgetServices(final int appWidgetId) {
		if (registeredWidgets.contains(appWidgetId)) {
			registeredWidgets.remove(new Integer(appWidgetId));
		}

		Intent serviceIntent = new Intent(context, WidgetUpdateService.class);
		serviceIntent
				.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

		serviceIntent.setData(Uri.parse(UPDATE_SERVICE_WIDGET_DATA
				+ appWidgetId));

		PendingIntent pendingIntent = PendingIntent.getService(context, 0,
				serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);

		AlarmManager alarmManager = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);

		alarmManager.cancel(pendingIntent);
	}

	public void clearWidgetPreferences(final int appWidgetId) {
		widgetSettingManager.removeAppWidgetPreferences(appWidgetId);
	}
}
